<template>
  <div class="task-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <!-- 第一行搜索字段 -->
        <div class="search-row">
          <el-form-item label="数据中心" class="search-form-item">
            <el-select 
              v-model="searchForm.dataCenter" 
              placeholder="请选择数据中心" 
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in dataCenterOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数据库实例" class="search-form-item">
            <el-select 
              v-model="searchForm.instance" 
              placeholder="请选择数据库实例" 
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in instanceOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数据库" class="search-form-item">
            <el-select 
              v-model="searchForm.database" 
              placeholder="请选择数据库" 
              clearable
              filterable
              allow-create
              default-first-option
              style="width: 200px"
              @change="handleDatabaseChange"
            >
              <el-option
                v-for="item in databaseOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数据表" class="search-form-item">
            <el-select 
              v-model="searchForm.table" 
              placeholder="请选择数据表" 
              clearable
              filterable
              allow-create
              default-first-option
              style="width: 200px"
              :loading="tableLoading"
            >
              <el-option
                v-for="item in tableOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </div>
        
        <!-- 第二行搜索字段 -->
        <div class="search-row">
          <el-form-item label="同步类型" class="search-form-item">
            <el-select 
              v-model="searchForm.taskType" 
              placeholder="请选择同步类型" 
              clearable
              style="width: 200px"
            >
              <el-option label="全量" value="0" />
              <el-option label="增量" value="1" />
              <el-option label="全量/增量" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="任务名称" class="search-form-item">
            <el-input
              v-model="searchForm.taskName"
              placeholder="请输入任务名称"
              clearable
              style="width: 213px"
            />
          </el-form-item>
          <el-form-item label="任务ID" class="search-form-item">
            <el-input
              v-model="searchForm.stTaskId"
              placeholder="请输入任务ID"
              clearable
              style="width: 200px"
            />
          </el-form-item>          
          <el-form-item class="search-form-item">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button @click="cleanCache">清空缓存</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>

    <!-- 任务列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>任务列表</span>
          <div class="header-actions">
            <div class="batch-actions">
              <el-button 
                type="success" 
                :disabled="selectedTasks.length === 0 || !canBatchStart"
                @click="handleBatchStart"
                :loading="batchStartLoading"
              >
                <el-icon><VideoPlay /></el-icon>
                批量启动 ({{ startableTasksCount }})
              </el-button>
              <el-button 
                type="warning" 
                :disabled="selectedTasks.length === 0 || !canBatchStop"
                @click="handleBatchStop"
                :loading="batchStopLoading"
              >
                <el-icon><VideoPause /></el-icon>
                批量停止 ({{ stoppableTasksCount }})
              </el-button>
            </div>
            <el-button type="primary" @click="handleAddTask">新建任务</el-button>
          </div>
        </div>
      </template>

      <el-table :data="taskList" border v-loading="loading" style="width: 100%" @expand-change="handleExpandChange" @selection-change="handleSelectionChange">
        <el-table-column type="expand" width="50">
          <template #default="props">
            <div class="table-detail-container">
              <el-row :gutter="16">
                <el-col :span="12">
                  <div class="table-section">
                    <div class="table-header">
                      <el-icon><Document /></el-icon>
                      <span>Source 表 ({{ getSourceTablesCount(props.row) }})</span>
                      <span id="kafka-lag" class="kafka-lag" style="color: #67c23a;"></span>
                    </div>
                    <el-table :data="getSourceTables(props.row)" size="small" border class="compact-table">
                      <el-table-column 
                        v-for="(header, index) in getSourceHeaders(props.row)" 
                        :key="index"
                        :prop="getSourceTableProp(index)"
                        :label="header" 
                        :min-width="80"
                      />
                    </el-table>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="table-section">
                    <div class="table-header">
                      <el-icon><Document /></el-icon>
                      <span>Sink 表 ({{ getSinkTablesCount(props.row) }})</span>
                    </div>
                    <el-table :data="getSinkTables(props.row)" size="small" border class="compact-table">
                      <el-table-column 
                        v-for="(header, index) in getSinkHeaders(props.row)" 
                        :key="index"
                        :prop="getSinkTableProp(index)"
                        :label="header" 
                        :min-width="80"
                      />
                    </el-table>
                  </div>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="domain" label="执行中心" min-width="100" show-overflow-tooltip>
          <template #default="scope">
            {{ getDataCenterName(scope.row.domain) }}
          </template>
        </el-table-column>
        <el-table-column prop="showName" label="任务名称" min-width="300" show-overflow-tooltip />
        <el-table-column prop="taskId" label="任务ID" min-width="120" show-overflow-tooltip />
        <el-table-column prop="syncConfigId" label="配置ID" min-width="50" show-overflow-tooltip>
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              @click="handleViewConfig(scope.row.syncConfigId)"
            >
              {{ scope.row.syncConfigId }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="taskType" label="同步模式" min-width="80" show-overflow-tooltip>
          <template #default="scope">
            {{ getTaskTypeText(scope.row.taskType) }}
          </template>
        </el-table-column>
        <el-table-column prop="sourcePlugin" label="source插件" min-width="80" show-overflow-tooltip />
        <el-table-column prop="sinkPlugin" label="sink插件" min-width="80" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" min-width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="130" show-overflow-tooltip />
        <el-table-column prop="updateTime" label="更新时间" min-width="130" show-overflow-tooltip />
        <el-table-column label="监控" min-width="80" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleMonitorTask(scope.row)">
              <el-icon><Monitor /></el-icon>
              监控
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleViewTask(scope.row)">查看</el-button>
              <el-button
              type="success" 
              link 
              @click="handleExecuteTask(scope.row)"
              :disabled="scope.row.status == 1"
            >执行</el-button>
              <el-button
                type="warning"
              link 
                @click="handleStopTask(scope.row)"
              :disabled="scope.row.status !== 1"
            >停止</el-button>
            <el-button type="danger" link @click="handleDeleteTask(scope.row)">删除</el-button>
            <el-button type="info" link @click="handleCopyTask(scope.row)">复制</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 任务详情对话框 -->
    <el-dialog
      v-model="taskDetailDialog.visible"
      title="任务详情"
      width="900px"
    >
      <el-descriptions :column="2" border class="task-descriptions">
        <el-descriptions-item label="任务名称" :span="2" class="task-name-item">
          <div 
            v-if="!isEditing" 
            @dblclick="startEditing"
            class="editable-name"
          >
            <span class="task-name-text">{{ taskDetail.showName }}</span>
            <el-icon class="edit-icon"><Edit /></el-icon>
          </div>
          <el-input
            v-else
            v-model="editingName"
            @blur="handleNameUpdate"
            @keyup.enter="handleNameUpdate"
            ref="nameInput"
            class="name-input"
          />
        </el-descriptions-item>
        <el-descriptions-item label="配置ID" class="compact-item">{{ taskDetail.syncConfigId }}</el-descriptions-item>
        <el-descriptions-item label="状态" class="compact-item">
          <el-tag :type="getStatusType(taskDetail.status)">
            {{ getStatusText(taskDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="同步模式" class="compact-item">{{ getTaskTypeText(taskDetail.taskType) }}</el-descriptions-item>
        <el-descriptions-item label="source插件" class="compact-item">{{ taskDetail.sourcePlugin }}</el-descriptions-item>
        <el-descriptions-item label="sink插件" class="compact-item">{{ taskDetail.sinkPlugin }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" class="compact-item">{{ taskDetail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" class="compact-item">{{ taskDetail.updateTime }}</el-descriptions-item>
      </el-descriptions>
      
      <el-tabs v-model="activeTab" class="template-tabs">
        <el-tab-pane label="任务模板" name="template">
          <div class="template-content">
            <div class="template-header">
              <h4>任务模板内容</h4>
              <div class="template-actions">
                <el-button 
                  v-if="isKafkaPlugin"
                  type="warning" 
                  @click="handleCheckKafkaTopic"
                  :loading="checkingTopic"
                >
                  预检Topic
                </el-button>
                <el-button @click="handleFormatJson">格式化</el-button>
                <el-button type="primary" @click="handleSaveTemplate" :loading="saving">保存</el-button>
              </div>
            </div>
            <el-input
              v-model="taskDetail.templateContent"
              type="textarea"
              :rows="15"
              class="template-editor"
              placeholder="请输入任务模板内容"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane 
          v-if="taskDetail.sourcePlugin === 'kafka'" 
          label="Kafka模板" 
          name="kafka"
        >
          <div class="kafka-template">
            <el-table :data="kafkaTemplates" border style="width: 100%">
              <el-table-column prop="topic" label="Topic" min-width="120" show-overflow-tooltip />
              <el-table-column prop="sourceDataCenter" label="源数据中心" min-width="120" show-overflow-tooltip />
              <el-table-column prop="sourceInstance" label="源数据实例" min-width="120" show-overflow-tooltip />
              <el-table-column prop="sourceDatabase" label="源库" min-width="120" show-overflow-tooltip />
              <el-table-column prop="sourceTable" label="源表" min-width="120" show-overflow-tooltip />
              <el-table-column prop="targetDataCenter" label="目标数据中心" min-width="120" show-overflow-tooltip />
              <el-table-column prop="targetInstance" label="目标数据实例" min-width="120" show-overflow-tooltip />
              <el-table-column prop="targetDatabase" label="目标库" min-width="120" show-overflow-tooltip />
              <el-table-column prop="targetTable" label="目标表" min-width="120" show-overflow-tooltip />
              <el-table-column label="操作" width="120" fixed="right" align="center">
                <template #default="scope">
                  <el-button type="primary" link @click="handleViewKafkaTemplate(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- Kafka模板详情对话框 -->
    <el-dialog
      v-model="kafkaTemplateDialog.visible"
      title="Kafka模板详情"
      :width="'auto'"
      :style="{ maxWidth: '90vw' }"
    >
      <div class="template-content">
        <div class="template-header">
          <h4>Schema模板内容</h4>
          <div class="template-actions">
            <el-button @click="handleFormatKafkaJson">格式化</el-button>
            <el-button type="primary" @click="handleSaveKafkaTemplate" :loading="saving">保存</el-button>
            <el-button 
              type="success" 
              @click="handleExecuteKafkaTemplate"
              :loading="executing"
            >执行</el-button>
          </div>
        </div>
        <el-input
          v-model="kafkaTemplateDialog.content"
          type="textarea"
          :rows="15"
          class="template-editor"
        />
      </div>
    </el-dialog>

    <!-- 复制对话框 -->
    <el-dialog
      v-model="copyDialog.visible"
      title="复制任务"
      width="600px"
    >
      <el-form :model="copyDialog.form" label-width="120px">
        <el-form-item label="源数据中心">
          <el-select 
            v-model="copyDialog.form.sourceDataCenter" 
            placeholder="请选择源数据中心"
            style="width: 100%"
          >
            <el-option
              v-for="item in dataCenterOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="源数据库实例">
          <el-select 
            v-model="copyDialog.form.sourceInstance" 
            placeholder="请选择源数据库实例"
            style="width: 100%"
          >
            <el-option
              v-for="item in copyDialog.sourceInstanceOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标数据中心">
          <el-select 
            v-model="copyDialog.form.targetDataCenter" 
            placeholder="请选择目标数据中心"
            style="width: 100%"
          >
            <el-option
              v-for="item in dataCenterOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标数据库实例">
          <el-select 
            v-model="copyDialog.form.targetInstance" 
            placeholder="请选择目标数据库实例"
            style="width: 100%"
          >
            <el-option
              v-for="item in copyDialog.targetInstanceOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="源库正则替换">
          <el-input
            v-model="copyDialog.form.sourceDbReplaceRegex"
            placeholder="非必填，源库正则替换表达式，例如：(.*)_en -> $1_fr"
            clearable
          />
        </el-form-item>
        <el-form-item label="源表正则替换">
          <el-input
            v-model="copyDialog.form.sourceTbReplaceRegex"
            placeholder="非必填，源表正则替换表达式，例如：(.*)_en -> $1_fr"
            clearable
          />
        </el-form-item>
        <el-form-item label="目标库正则替换">
          <el-input
            v-model="copyDialog.form.targetDbReplaceRegex"
            placeholder="非必填，目标库正则表达式，例如：(.*)_en -> $1_fr"
            clearable
          />
        </el-form-item>
        <el-form-item label="目标表正则替换">
          <el-input
            v-model="copyDialog.form.targetTbReplaceRegex"
            placeholder="非必填，目标表正则表达式，例如：(.*)_en -> $1_fr"
            clearable
          />
        </el-form-item>

        <!-- 添加默认值配置部分 -->
        <el-form-item label="字段默认值">
          <div class="default-value-config">
            <el-button 
              type="primary" 
              size="small" 
              @click="showDefaultValueDialog"
            >
              修改默认值
            </el-button>
            <div v-if="copyDialog.form.defaultValues.length > 0" class="default-value-list">
              <el-tag
                v-for="(item, index) in copyDialog.form.defaultValues"
                :key="index"
                class="default-value-tag"
                closable
                @close="removeDefaultValue(index)"
              >
                {{ item.fieldName }}: {{ item.defaultValue }}
              </el-tag>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="copyDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitCopy" :loading="copyDialog.loading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加默认值配置对话框 -->
    <el-dialog
      v-model="defaultValueDialog.visible"
      title="配置字段默认值"
      width="500px"
      append-to-body
    >
      <el-form :model="defaultValueDialog.form" label-width="100px">
        <el-form-item label="字段名">
          <el-input
            v-model="defaultValueDialog.form.fieldName"
            placeholder="请输入字段名"
            clearable
          />
        </el-form-item>
        <el-form-item label="默认值">
          <el-input
            v-model="defaultValueDialog.form.defaultValue"
            placeholder="请输入默认值"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="defaultValueDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="addDefaultValue">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Kafka执行对话框 -->
    <el-dialog
      v-model="kafkaExecuteDialog.visible"
      title="执行Kafka消费任务"
      width="500px"
    >
      <div style="margin-bottom: 20px;">
        <h4 style="margin: 0 0 16px 0; color: #606266;">选择消费起始位置：</h4>
        
        <el-radio-group v-model="kafkaExecuteDialog.consumeOption" style="width: 100%;">
          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px;">
            <el-radio value="none" style="margin-right: 0;">
              <div style="margin-left: 4px;">
                <div style="font-weight: 500;">none</div>
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">从上次的保存点开始消费</div>
              </div>
            </el-radio>
            
            <el-radio value="latest" style="margin-right: 0;">
              <div style="margin-left: 4px;">
                <div style="font-weight: 500;">latest</div>
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">从最新消息开始</div>
              </div>
            </el-radio>
            
            <el-radio value="earliest" style="margin-right: 0;">
              <div style="margin-left: 4px;">
                <div style="font-weight: 500;">earliest</div>
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">从初始消息开始消费</div>
              </div>
            </el-radio>
            
            <el-radio value="timestamp" style="margin-right: 0;">
              <div style="margin-left: 4px;">
                <div style="font-weight: 500;">timestamp</div>
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">从指定的时间点开始消费</div>
              </div>
            </el-radio>
          </div>
          
          <div v-if="kafkaExecuteDialog.consumeOption === 'timestamp'" style="margin-top: 16px;">
            <el-form-item label="开始时间：" label-width="20px">
              <el-date-picker
                v-model="kafkaExecuteDialog.startTime"
                type="datetime"
                placeholder="请选择开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%;"
              />
            </el-form-item>
          </div>
        </el-radio-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancelKafkaExecute">取消</el-button>
          <el-button type="primary" @click="handleExecuteKafkaTask" :loading="kafkaExecuteDialog.loading">
            确认执行
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- MySQL CDC执行对话框 -->
    <el-dialog
      v-model="mysqlCdcExecuteDialog.visible"
      title="执行MySQL同步任务"
      width="500px"
    >
      <div style="margin-bottom: 20px;">
        <h4 style="margin: 0 0 16px 0; color: #606266;">选择消费起始位置：</h4>
        
        <el-radio-group v-model="mysqlCdcExecuteDialog.consumeOption" style="width: 100%;">
          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px;">
            <el-radio value="none" style="margin-right: 0;">
              <div style="margin-left: 4px;">
                <div style="font-weight: 500;">none</div>
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">从上次的保存点开始</div>
              </div>
            </el-radio>
            
            <el-radio value="latest" style="margin-right: 0;">
              <div style="margin-left: 4px;">
                <div style="font-weight: 500;">latest</div>
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">从最新binlog开始</div>
              </div>
            </el-radio>
            
            <el-radio value="initial" style="margin-right: 0;">
              <div style="margin-left: 4px;">
                <div style="font-weight: 500;">initial</div>
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">全量/增量同步，同步表太多任务可能不稳定</div>
              </div>
            </el-radio>
            
            <el-radio value="specific" style="margin-right: 0;">
              <div style="margin-left: 4px;">
                <div style="font-weight: 500;">specific</div>
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">从指定的binlog开始消费</div>
              </div>
            </el-radio>
          </div>
          
          <div v-if="mysqlCdcExecuteDialog.consumeOption === 'specific'" style="margin-top: 16px;">
            <el-form-item label="Binlog文件：" label-width="20px">
              <div style="display: flex; flex-direction: column; align-items: flex-start;">
                <el-input
                  v-model="mysqlCdcExecuteDialog.binlogPosition"
                  placeholder="请输入binlog文件"
                  style="width: 300px;"
                  clearable
                />
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                  格式示例：mysql-bin.000001
                </div>
              </div>
            </el-form-item>
          </div>
        </el-radio-group>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancelMysqlCdcExecute">取消</el-button>
          <el-button type="primary" @click="handleExecuteMysqlCdcTask" :loading="mysqlCdcExecuteDialog.loading">
            确认执行
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getTaskList, deleteTask, executeTask, stopTask, getTaskDetail, checkKafkaTopic, getTaskTables, showKafkaLag } from '@/api/task'
import { getDataCenters, getInstances, getDatabases, getTables, cleanCache as cleanCacheAPI } from '@/api/datasourceQuery'
import request from '@/utils/request'
import { useRouter } from 'vue-router'
import { Edit, Monitor, VideoPlay, VideoPause, Document, Loading } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  stTaskId: '',
  taskName: '',
  taskType: '',
  dataCenter: '',
  instance: '',
  database: '',
  table: ''
})

// 选项数据
const dataCenterOptions = ref([])
const instanceOptions = ref([])
const databaseOptions = ref([])
const tableOptions = ref([])

// 加载状态
const tableLoading = ref(false)

// 数据中心缓存变量
let dataCenterCacheData = null

// 任务列表数据
const taskList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表数据缓存
const tableDataCache = ref(new Map())

// 批量操作相关
const selectedTasks = ref([])
const batchStartLoading = ref(false)
const batchStopLoading = ref(false)

// 计算可启动和可停止的任务数量
const startableTasksCount = computed(() => {
  return selectedTasks.value.filter(task => task.status !== 1).length
})

const stoppableTasksCount = computed(() => {
  return selectedTasks.value.filter(task => task.status === 1).length
})

// 计算是否可以执行批量操作
const canBatchStart = computed(() => {
  return startableTasksCount.value > 0
})

const canBatchStop = computed(() => {
  return stoppableTasksCount.value > 0
})

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedTasks.value = selection
}

// 任务详情对话框
const taskDetailDialog = reactive({
  visible: false
})
const taskDetail = reactive({
  name: '',
  syncConfigId: '',
  status: '',
  createTime: '',
  updateTime: '',
  templateContent: ''
})

// 保存状态
const saving = ref(false)

// 选项卡
const activeTab = ref('template')

// 监听选项卡切换
watch(activeTab, (newValue) => {
  if (newValue === 'kafka' && taskDetail.sourcePlugin === 'kafka') {
    fetchKafkaTemplates()
  }
})

// Kafka模板数据
const kafkaTemplates = ref([])

// Kafka模板详情对话框
const kafkaTemplateDialog = reactive({
  visible: false,
  content: '',
  id: '',
  status: '0'
})

// 执行状态
const executing = ref(false)
const stopping = ref(false)

// 添加预检状态
const checkingTopic = ref(false)

// 添加判断是否为 Kafka 插件的方法
const isKafkaPlugin = computed(() => {
  try {
    return taskDetail.sourcePlugin === 'kafka' || taskDetail.sinkPlugin === 'kafka'
  } catch (error) {
    return false
  }
})

const router = useRouter()
const SEARCH_FORM_KEY = "search_form_key"

// 获取数据中心列表
const fetchDataCenterList = async () => {
  try {
    const response = await getDataCenters()
    dataCenterOptions.value = response.map(item => ({
      code: item.code,
      name: item.name
    }))
    dataCenterCacheData = response.map(item => ({
      domain: item.domain,
      name: item.name
    }))
  } catch (error) {
    console.error('获取数据中心列表失败：', error)
    ElMessage.error('获取数据中心列表失败')
  }
}

// 获取任务列表
const fetchTaskList = async () => {
  const saved = localStorage.getItem(SEARCH_FORM_KEY)
  if (saved) {
    try {
      const parsed = JSON.parse(saved)
      Object.keys(searchForm).forEach(key => {
        if (parsed[key] !== undefined) {
          searchForm[key] = parsed[key]
        }
      })
    } catch (e) {
      // ignore parse error
    }
  }
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      dataCenter: searchForm.dataCenter,
      instance: searchForm.instance,
      database: searchForm.database,
      table: searchForm.table,
      jobName: searchForm.taskName,
      taskType: searchForm.taskType,
      stTaskId: searchForm.stTaskId
    }

    const response = await getTaskList(params)
    if (response && typeof response === 'object') {
      taskList.value = response.tasks || response || []
      total.value = response.total || response.length || 0
    } else {
      taskList.value = []
      total.value = 0
    }

  } catch (error) {
    console.error('获取任务列表失败：', error)
    ElMessage.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

// 当展开行时，调用接口获取表数据
const handleExpandChange = async (row, expandedRows) => {
  if (row && expandedRows.includes(row)) {
    try {
      const showTables = await getTaskTables(row.id)
      tableDataCache.value.set(row.id, showTables)
      
      // 如果是 Kafka 任务，获取 Lag 数据
      if (row.sourcePlugin === 'kafka') {
        getKafkaLag(row)
      }
    } catch (error) {
      ElMessage.error('获取表数据失败')
    }
  }
}

// 获取 Source 表数据
const getSourceTables = (row) => {
  const cachedData = tableDataCache.value.get(row.id)
  return cachedData ? cachedData.sourceTables : []
}

// 获取 Sink 表数据
const getSinkTables = (row) => {
  const cachedData = tableDataCache.value.get(row.id)
  return cachedData ? cachedData.sinkTables : []
}

// 获取 Source 表头
const getSourceHeaders = (row) => {
  const cachedData = tableDataCache.value.get(row.id)
  return cachedData ? cachedData.sourceHeaders : []
}

// 获取 Sink 表头
const getSinkHeaders = (row) => {
  const cachedData = tableDataCache.value.get(row.id)
  return cachedData ? cachedData.sinkHeaders : []
}

// 获取 Source 表数量
const getSourceTablesCount = (row) => {
  return getSourceTables(row).length
}

// Kafka Lag 数据缓存，避免重复请求
const kafkaLagCache = ref(new Map())

// 获取 kafka lag 数据，仅当 sourcePlugin 为 kafka 时，才显示 kafka lag 数据
const getKafkaLag = async (row) => {
  if (row.sourcePlugin === 'kafka') {
    // 检查是否已经获取过数据
    if (kafkaLagCache.value.has(row.id)) {
      return kafkaLagCache.value.get(row.id)
    }
    
    try {
      const response = await showKafkaLag(row.id)
      const lagValue = response || '0'
      // 缓存数据
      kafkaLagCache.value.set(row.id, lagValue)
      // 填充 Kafka Lag 数据到对应的元素
      const kafkaLagElement = document.getElementById('kafka-lag')
      if (kafkaLagElement) {
        kafkaLagElement.innerHTML = `Kafka Lag (${lagValue})`
      }
      return lagValue
    } catch (error) {
      console.error('获取Kafka Lag失败：', error)
      // 错误时也填充默认值
      const kafkaLagElement = document.getElementById('kafka-lag')
      if (kafkaLagElement) {
        kafkaLagElement.innerHTML = `获取Lag数据异常`
      }
      return '0'
    }
  }
}

// 获取 Sink 表数量
const getSinkTablesCount = (row) => {
  return getSinkTables(row).length
}

// 获取 Source 表格属性名
const getSourceTableProp = (index) => {
  const propMap = {
    0: 'pattern',
    1: 'database', 
    2: 'table'
  }
  return propMap[index] || `col${index}`
}

// 获取 Sink 表格属性名
const getSinkTableProp = (index) => {
  const propMap = {
    0: 'pattern',
    1: 'database',
    2: 'table'
  }
  return propMap[index] || `col${index}`
}

// 获取任务详情
const fetchTaskDetail = async (id) => {
  try {
    const response = await getTaskDetail(id)
    Object.assign(taskDetail, response)
    // 自动格式化JSON
    taskDetail.templateContent = formatJson(taskDetail.templateContent)
  } catch (error) {
    console.error('获取任务详情失败：', error)
    ElMessage.error('获取任务详情失败')
  }
}

// 状态相关方法
const getStatusType = (status) => {
  const statusMap = {
    '0': 'info',
    '1': 'warning',
    '2': 'primary',
    '3': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    '0': '待执行',
    '1': '执行中',
    '2': '已完成',
    '3': '失败',
    '4': '已停止',
    '5': '已退出'
  }
  return statusMap[status] || '未知'
}

// 同步模式转换方法
const getTaskTypeText = (taskType) => {
  const taskTypeMap = {
    '0': '全量',
    '1': '增量',
    '2': '全量/增量'
  }
  return taskTypeMap[taskType] || taskType || '未知'
}

// 根据 domain 获取数据中心名称
const getDataCenterName = (domain) => {
  if (!domain || !dataCenterCacheData) {
    return domain || '未知'
  }
  
  // 从缓存列表中查找匹配的域名
  const center = dataCenterCacheData.find(item => item.domain === domain)
  return center ? center.name : domain
}

// 监听数据中心变化
watch(() => searchForm.dataCenter, async (newValue) => {
  if (newValue) {
    await fetchInstanceList(newValue)
  } else {
    instanceOptions.value = []
    searchForm.instance = ''
    databaseOptions.value = []
    searchForm.database = ''
    tableOptions.value = []
    searchForm.table = ''
  }
})

// 监听数据库实例变化
watch(() => searchForm.instance, async (newValue) => {
  if (newValue) {
    await fetchDatabaseList(newValue)
  } else {
    databaseOptions.value = []
    searchForm.database = ''
    tableOptions.value = []
    searchForm.table = ''
  }
})

// 监听数据库变化
watch(() => searchForm.database, async (newValue) => {
  if (newValue && searchForm.dataCenter && searchForm.instance) {
    await fetchTableList(newValue)
  } else {
    tableOptions.value = []
    searchForm.table = ''
  }
})

// 获取数据库实例列表
const fetchInstanceList = async (dataCenterCode) => {
  try {
    const response = await getInstances(`${dataCenterCode}`)
    instanceOptions.value = response.map(item => ({
      id: item,
      name: item
    }))
  } catch (error) {
    console.error('获取数据库实例列表失败：', error)
    ElMessage.error('获取数据库实例列表失败')
    instanceOptions.value = []
  }
}

// 获取数据库列表
const fetchDatabaseList = async (instanceId) => {
  try {
    const response = await getDatabases(`${searchForm.dataCenter}`, `${instanceId}`)
    databaseOptions.value = response || []
  } catch (error) {
    console.error('获取数据库列表失败：', error)
    ElMessage.error('获取数据库列表失败')
    databaseOptions.value = []
  }
}

// 处理数据库选择变化
const handleDatabaseChange = async (database) => {
  searchForm.table = '' // 清空表选择
  tableOptions.value = [] // 清空表选项
  
  if (database && searchForm.dataCenter && searchForm.instance) {
    await fetchTableList(database)
  }
}

// 获取表列表
const fetchTableList = async (database) => {
  if (!searchForm.dataCenter || !searchForm.instance || !database) return
  
  try {
    tableLoading.value = true
    const response = await getTables(searchForm.dataCenter, searchForm.instance, database)
    tableOptions.value = response || []
  } catch (error) {
    console.error('获取表列表失败：', error)
    ElMessage.error('获取表列表失败')
    tableOptions.value = []
  } finally {
    tableLoading.value = false
  }
}

// 搜索相关方法
const handleSearch = () => {
  localStorage.setItem(SEARCH_FORM_KEY, JSON.stringify(searchForm))
  currentPage.value = 1
  fetchTaskList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    stTaskId: '',
    taskName: '',
    taskType: '',
    dataCenter: '',
    instance: '',
    database: '',
    table: ''
  })
  instanceOptions.value = []
  databaseOptions.value = []
  tableOptions.value = []
  handleSearch()
}

// 清空缓存
const cleanCache = async () => {
  try {
    await cleanCacheAPI()
    
    // 清空本地缓存数据
    dataCenterCacheData = null
    dataCenterOptions.value = []
    instanceOptions.value = []
    databaseOptions.value = []
    tableOptions.value = []
    
    ElMessage.success('缓存清空成功')
    
    // 重新获取数据中心列表
    await fetchDataCenterList()
    
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      return
    }
    console.error('清空缓存失败：', error)
    ElMessage.error('清空缓存失败：' + (error.message || '未知错误'))
  }
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchTaskList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTaskList()
}

// 新建任务
const handleAddTask = () => {
  router.push('/sync')
}

const handleViewTask = async (row) => {
  taskDetailDialog.visible = true
  activeTab.value = 'template'  // 设置默认选项卡为任务模板
  await fetchTaskDetail(row.id)
}

const handleExecuteTask = async (row) => {
  try {
    // 检查是否为kafka源任务
    if (row.sourcePlugin === 'kafka') {
      // 显示kafka执行选项对话框
      await showKafkaExecuteDialog(row)
    } else if (row.sourcePlugin === 'mysql-cdc') {
      // 显示mysql-cdc执行选项对话框
      await showMysqlCdcExecuteDialog(row)
    } else {
      // 普通任务的确认对话框
      await ElMessageBox.confirm(
        '确认要执行该任务吗？',
        '执行任务',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      
      await executeTask(row.id)
      ElMessage.success('任务开始执行')
      fetchTaskList()
    }
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      // 用户取消或关闭对话框，不做任何操作
      return
    }
    console.error('执行任务失败：', error)
    ElMessage.error('执行任务失败：' + (error.message || '未知错误'))
  }
}

const handleStopTask = async (row) => {
  try {
    // 添加确认对话框
    await ElMessageBox.confirm(
      '是否需要执行保存点操作？',
      '停止任务',
      {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
        distinguishCancelAndClose: true
      }
    )
    
    // 用户点击"是"，执行带保存点的停止
    await stopTask(row.id, true)
    ElMessage.success('任务已停止（已执行保存点）')
    fetchTaskList()
  } catch (error) {
    if (error === 'cancel') {
      // 用户点击"否"，再次确认是否执行普通停止
      try {
        await ElMessageBox.confirm(
          '该任务即将取消，并且无法恢复！\n\n确认不进行保存点操作吗？',
          '危险操作警告',
          {
            confirmButtonText: '确认停止',
            cancelButtonText: '取消',
            type: 'error',
            distinguishCancelAndClose: true
          }
        )
        
        // 用户确认强制停止，执行普通停止
        await stopTask(row.id, false)
        ElMessage.success('任务已停止')
        fetchTaskList()
      } catch (confirmError) {
        if (confirmError === 'cancel' || confirmError === 'close') {
          // 用户取消强制停止，不做任何操作
          return
        } else {
          console.error('停止任务失败：', confirmError)
          ElMessage.error('停止任务失败：' + (confirmError.message || '未知错误'))
        }
      }
    } else if (error === 'close') {
      // 用户关闭对话框，不做任何操作
      return
    } else {
      console.error('停止任务失败：', error)
      ElMessage.error('停止任务失败：' + (error.message || '未知错误'))
    }
  }
}

const handleDeleteTask = (row) => {
  ElMessageBox.confirm('确认删除该任务吗？', '提示', {
      type: 'warning'
  }).then(async () => {
    try {
      await deleteTask(row.id)
      ElMessage.success('删除成功')
      fetchTaskList()
    } catch (error) {
      console.error('删除任务失败：', error)
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  })
}

// 监控任务
const handleMonitorTask = (row) => {
  // 根据任务的数据中心映射到集群参数
  const clusterMapping = {
    'https://fuxi-seatunnel-master-pt.cdreader.vip': 'seatunnel-tkept',
    'https://fuxi-seatunnel-master-fr.cdreader.vip': 'seatunnel-ccfr', 
    'https://fuxi-seatunnel-master-id.cdreader.vip': 'seatunnel-ccid',
    'https://fuxi-seatunnel-master-en.cdreader.vip': 'seatunnel-ccen',
    'https://fuxi-seatunnel-master-sp.cdreader.vip': 'seatunnel-ccsp',
    'https://fuxi-seatunnel-master-th.cdreader.vip': 'seatunnel-cyth', 
    'https://fuxi-seatunnel-master-ru.cdreader.vip': 'seatunnel-cyru',
    'https://fuxi-seatunnel-master-none-hkidc.cdreader.vip': 'seatunnel-hk',
	  'https://fuxi-seatunnel-master-none-cchk.cdreader.vip': 'seatunnel-cchk',
    'https://fuxi-seatunnel-master-none-fzidc.changdu.vip': 'seatunnel-idc',
    'https://fuxi-seatunnel-master-hk.cdreader.vip': 'seatunnel-cyhk', 
    'https://fuxi-seatunnel-master-video.cdreader.vip': 'seatunnel-video-tke',
    'https://fuxi-seatunnel-master-idc-stage.changdu.vip': 'seatunnel-stage',
    'https://fuxi-seatunnel-master-none-new-dev.changdu.ltd': 'seatunnel-test',
  }
  
  // 使用sourceDataCenter
  const monitorDomain = row.domain
  let cluster = clusterMapping[monitorDomain] || 'seatunnel-ccen' // 默认集群
  
  // 通过新标签页打开table页面并携带参数
  const routeData = router.resolve({
    path: '/monitor',
    query: {
      cluster: cluster,
      taskId: row.taskId,
      taskName: row.showName
    }
  })
  
  window.open(routeData.href, '_blank')
  
  ElMessage.success(`正在新标签页中打开 ${cluster} 集群的表格页面`)
}

// 批量启动任务
const handleBatchStart = async () => {
  const startableTasks = selectedTasks.value.filter(task => task.status !== 1)
  
  if (startableTasks.length === 0) {
    ElMessage.warning('所选任务中没有可启动的任务（只能启动非运行中的任务）')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确认要批量启动 ${startableTasks.length} 个任务吗？`,
      '批量启动任务',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    batchStartLoading.value = true
    const taskIds = startableTasks.map(task => task.id)
    
    await request.post('/task/submit/batch', {
      taskIds: taskIds
    })
    
    ElMessage.success(`成功启动 ${startableTasks.length} 个任务`)
    selectedTasks.value = []
    fetchTaskList() // 刷新列表
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      return
    }
    console.error('批量启动任务失败：', error)
    ElMessage.error('批量启动失败：' + (error.message || '未知错误'))
  } finally {
    batchStartLoading.value = false
  }
}

// 批量停止任务
const handleBatchStop = async () => {
  const stoppableTasks = selectedTasks.value.filter(task => task.status === 1)
  
  if (stoppableTasks.length === 0) {
    ElMessage.warning('所选任务中没有可停止的任务（只能停止运行中的任务）')
    return
  }
  
  try {
    // 第一步：确认是否停止任务
    await ElMessageBox.confirm(
      `确认要批量停止 ${stoppableTasks.length} 个任务吗？`,
      '批量停止任务',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 第二步：询问是否需要保存点
    let savepointChoice = false
    try {
      await ElMessageBox.confirm(
        '是否需要执行保存点操作？',
        '保存点选择',
        {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      savepointChoice = true // 用户选择执行保存点
    } catch (action) {
      if (action === 'cancel') {
        // 用户选择直接停止，再次确认
        try {
          await ElMessageBox.confirm(
            '该批量任务即将取消，并且无法恢复！\n\n确认要强制停止所有选中的任务吗？',
            '危险操作警告',
            {
              confirmButtonText: '确认停止',
              cancelButtonText: '取消',
              type: 'error',
              distinguishCancelAndClose: true
            }
          )
          savepointChoice = false // 用户确认直接停止
        } catch (confirmError) {
          if (confirmError === 'cancel' || confirmError === 'close') {
            // 用户取消批量停止，退出整个操作
            return
          }
        }
      } else {
        // 用户关闭对话框，取消整个操作
        return
      }
    }
    
    batchStopLoading.value = true
    const taskIds = stoppableTasks.map(task => task.id)
    
    await request.post('/task/stop/batch', {
      taskIds: taskIds,
      savepoint: savepointChoice
    })
    
    const savepointText = savepointChoice ? '（已执行保存点）' : '（直接停止）'
    ElMessage.success(`成功停止 ${stoppableTasks.length} 个任务${savepointText}`)
    selectedTasks.value = []
    fetchTaskList() // 刷新列表
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      return
    }
    console.error('批量停止任务失败：', error)
    ElMessage.error('批量停止失败：' + (error.message || '未知错误'))
  } finally {
    batchStopLoading.value = false
  }
}

// JSON格式化方法
const formatJson = (jsonString) => {
  try {
    const jsonObj = JSON.parse(jsonString)
    return JSON.stringify(jsonObj, null, 2)
  } catch (error) {
    console.error('JSON格式化失败：', error)
    return jsonString
  }
}

// 格式化JSON
const handleFormatJson = () => {
  try {
    taskDetail.templateContent = formatJson(taskDetail.templateContent)
    ElMessage.success('格式化成功')
  } catch (error) {
    ElMessage.error('JSON格式不正确，无法格式化')
  }
}

// 保存模板内容
const handleSaveTemplate = async () => {
  try {
    // 保存前验证JSON格式
    JSON.parse(taskDetail.templateContent)
    
    saving.value = true
    await request.post('/task/update/template', {
      id: taskDetail.id,
      templateContent: taskDetail.templateContent
    })
    ElMessage.success('保存成功')
    taskDetailDialog.visible = false
    fetchTaskList() // 刷新列表
  } catch (error) {
    if (error instanceof SyntaxError) {
      ElMessage.error('JSON格式不正确，请检查')
    } else {
      console.error('保存模板失败：', error)
      ElMessage.error('保存失败：' + (error.message || '未知错误'))
    }
  } finally {
    saving.value = false
  }
}

// 获取Kafka模板列表
const fetchKafkaTemplates = async () => {
  try {
    const response = await request.get('/datakafkatemplate/list', {
      params: {
        syncConfigId: taskDetail.syncConfigId
      }
    })
    kafkaTemplates.value = response || []
  } catch (error) {
    console.error('获取Kafka模板列表失败：', error)
    ElMessage.error('获取Kafka模板列表失败')
  }
}

// 保存Kafka模板
const handleSaveKafkaTemplate = async () => {
  try {
    // 保存前验证JSON格式
    JSON.parse(kafkaTemplateDialog.content)
    
    saving.value = true
    await request.put('/datakafkatemplate/update', {
      id: kafkaTemplateDialog.id,
      templateContent: kafkaTemplateDialog.content
    })
    ElMessage.success('保存成功')
    kafkaTemplateDialog.visible = false
    fetchKafkaTemplates() // 刷新列表
  } catch (error) {
    if (error instanceof SyntaxError) {
      ElMessage.error('JSON格式不正确，请检查')
    } else {
      console.error('保存Kafka模板失败：', error)
      ElMessage.error('保存失败：' + (error.message || '未知错误'))
    }
  } finally {
    saving.value = false
  }
}

// 查看Kafka模板详情
const handleViewKafkaTemplate = (row) => {
  kafkaTemplateDialog.id = row.id
  kafkaTemplateDialog.content = formatJson(row.templateContent)
  kafkaTemplateDialog.status = row.status || '0'
  kafkaTemplateDialog.visible = true
}

// 格式化Kafka模板JSON
const handleFormatKafkaJson = () => {
  try {
    kafkaTemplateDialog.content = formatJson(kafkaTemplateDialog.content)
    ElMessage.success('格式化成功')
  } catch (error) {
    ElMessage.error('JSON格式不正确，无法格式化')
  }
}

// 执行Kafka模板
const handleExecuteKafkaTemplate = async () => {
  try {
    executing.value = true
    await request.get(`/task/submitsubjob/${kafkaTemplateDialog.id}`)
    ElMessage.success('执行成功')
    kafkaTemplateDialog.status = '1'
    kafkaTemplateDialog.visible = false  // 关闭对话框
    fetchKafkaTemplates()  // 刷新列表
  } catch (error) {
    console.error('执行Kafka模板失败：', error)
    ElMessage.error('执行失败：' + (error.message || '未知错误'))
  } finally {
    executing.value = false
  }
}

// 监听source插件变化
watch(() => taskDetail.sourcePlugin, (newValue) => {
  if (newValue === 'kafka') {
    fetchKafkaTemplates()
  }
})

// 查看配置
const handleViewConfig = async (configId) => {
  try {
    const response = await request.get(`/sync/config/${configId}`)
    // 将配置数据存储到 localStorage
    localStorage.setItem('syncConfigData', JSON.stringify(response))
    // 跳转到同步页面
    router.push('/sync')
  } catch (error) {
    console.error('获取配置数据失败：', error)
    ElMessage.error('获取配置数据失败：' + (error.message || '未知错误'))
  }
}

// 添加预检方法
const handleCheckKafkaTopic = async () => {
  try {
    // 添加确认弹窗
    await ElMessageBox.confirm(
      '此操作将会创建相关topic及分区（腾讯云Kafka只允许通过管理后台对已存在的topic进行分区扩展），请知晓并确认是否继续',
      '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
    )
    
    checkingTopic.value = true
    
    // 检查必要的配置项
    if (!taskDetail.id) {
      ElMessage.warning('任务信息不完整')
      return
    }
    
    // 发起预检请求
    const response = await checkKafkaTopic(taskDetail.id)
    ElMessage.success('Topic 预检成功')
  } catch (error) {
    if (error === 'cancel') {
      return
    }
    ElMessage.error('Topic 预检失败：' + (error.response.data.msg || '未知错误'))
  } finally {
    checkingTopic.value = false
  }
}

// 复制对话框数据
const copyDialog = reactive({
  visible: false,
  loading: false,
  taskId: '',
  form: {
    sourceDataCenter: '',
    sourceInstance: '',
    targetDataCenter: '',
    targetInstance: '',
    sourceDbReplaceRegex: '',
    sourceTbReplaceRegex: '',
    targetDbReplaceRegex: '',
    targetTbReplaceRegex: '',
    defaultValues: []
  },
  sourceInstanceOptions: [],
  targetInstanceOptions: []
})

// 监听源数据中心变化
watch(() => copyDialog.form.sourceDataCenter, async (newValue) => {
  if (newValue) {
    await fetchCopyInstanceList(newValue, 'source')
  } else {
    copyDialog.sourceInstanceOptions = []
    copyDialog.form.sourceInstance = ''
  }
})

// 监听目标数据中心变化
watch(() => copyDialog.form.targetDataCenter, async (newValue) => {
  if (newValue) {
    await fetchCopyInstanceList(newValue, 'target')
  } else {
    copyDialog.targetInstanceOptions = []
    copyDialog.form.targetInstance = ''
  }
})

// 获取数据库实例列表
const fetchCopyInstanceList = async (dataCenterCode, type) => {
  try {
    const response = await getInstances(`${dataCenterCode}`)
    const options = response.map(item => ({
      id: item,
      name: item
    }))
    if (type === 'source') {
      copyDialog.sourceInstanceOptions = options
    } else {
      copyDialog.targetInstanceOptions = options
    }
  } catch (error) {
    console.error('获取数据库实例列表失败：', error)
    ElMessage.error('获取数据库实例列表失败')
    if (type === 'source') {
      copyDialog.sourceInstanceOptions = []
    } else {
      copyDialog.targetInstanceOptions = []
    }
  }
}

// 打开复制对话框
const handleCopyTask = (row) => {
  copyDialog.taskId = row.syncConfigId  // 修改为使用配置ID
  copyDialog.visible = true
  // 重置表单
  copyDialog.form = {
    sourceDataCenter: '',
    sourceInstance: '',
    targetDataCenter: '',
    targetInstance: '',
    sourceDbReplaceRegex: '',
    sourceTbReplaceRegex: '',
    targetDbReplaceRegex: '',
    targetTbReplaceRegex: '',
    defaultValues: []
  }
  copyDialog.sourceInstanceOptions = []
  copyDialog.targetInstanceOptions = []
}

// 提交复制请求
const submitCopy = async () => {
  try {
    // 验证表单
    if (!copyDialog.form.sourceDataCenter || !copyDialog.form.sourceInstance ||
        !copyDialog.form.targetDataCenter || !copyDialog.form.targetInstance) {
      ElMessage.warning('请填写完整的复制信息')
      return
    }

    copyDialog.loading = true
    const response = await request.post(`/sync/config/generate/copy/${copyDialog.taskId}`, copyDialog.form)
    ElMessage.success('复制成功')
    copyDialog.visible = false
    fetchTaskList() // 刷新列表
  } catch (error) {
    console.error('复制失败：', error)
    ElMessage.error('复制失败：' + (error.response?.data?.msg || '未知错误'))
  } finally {
    copyDialog.loading = false
  }
}

// 添加编辑状态相关的响应式变量
const isEditing = ref(false)
const editingName = ref('')
const nameInput = ref(null)

// 开始编辑
const startEditing = () => {
  isEditing.value = true
  editingName.value = taskDetail.showName
  // 等待DOM更新后聚焦输入框
  nextTick(() => {
    nameInput.value?.focus()
  })
}

// 处理名称更新
const handleNameUpdate = async () => {
  try {
    if (editingName.value === taskDetail.showName) {
      isEditing.value = false
      return
    }
    
    await request.post('/task/update/taskname', {
      id: taskDetail.id,
      showName: editingName.value
    })
    // 更新本地数据
    taskDetail.showName = editingName.value
    // 更新列表中的数据
    const index = taskList.value.findIndex(task => task.id === taskDetail.id)
    if (index !== -1) {
      taskList.value[index].showName = editingName.value
    }
    
    ElMessage.success('更新成功')
    isEditing.value = false
  } catch (error) {
    console.error('更新任务名称失败：', error)
    ElMessage.error('更新失败：' + (error.message || '未知错误'))
    // 恢复原值
    editingName.value = taskDetail.showName
  }
}

// 在 script setup 部分添加相关数据和方法
const defaultValueDialog = reactive({
  visible: false,
  form: {
    fieldName: '',
    defaultValue: ''
  }
})

// 显示默认值配置对话框
const showDefaultValueDialog = () => {
  defaultValueDialog.visible = true
  defaultValueDialog.form.fieldName = ''
  defaultValueDialog.form.defaultValue = ''
}

// 添加默认值
const addDefaultValue = () => {
  if (!defaultValueDialog.form.fieldName || !defaultValueDialog.form.defaultValue) {
    ElMessage.warning('请填写完整的字段名和默认值')
    return
  }

  // 检查是否已存在相同字段名
  const exists = copyDialog.form.defaultValues.some(
    item => item.fieldName === defaultValueDialog.form.fieldName
  )
  if (exists) {
    ElMessage.warning('该字段名已存在')
    return
  }

  copyDialog.form.defaultValues.push({
    fieldName: defaultValueDialog.form.fieldName,
    defaultValue: defaultValueDialog.form.defaultValue
  })

  defaultValueDialog.visible = false
  ElMessage.success('添加默认值成功')
}

// 移除默认值
const removeDefaultValue = (index) => {
  copyDialog.form.defaultValues.splice(index, 1)
}

// 在重置表单时清空默认值
const resetCopyForm = () => {
  copyDialog.form = {
    sourceDataCenter: '',
    sourceInstance: '',
    targetDataCenter: '',
    targetInstance: '',
    sourceDbReplaceRegex: '',
    sourceTbReplaceRegex: '',
    targetDbReplaceRegex: '',
    targetTbReplaceRegex: '',
    defaultValues: []
  }
}

// Kafka执行对话框
const kafkaExecuteDialog = reactive({
  visible: false,
  loading: false,
  taskData: null,
  consumeOption: 'none', // none, latest, earliest, timestamp
  startTime: ''
})

// MySQL CDC执行对话框
const mysqlCdcExecuteDialog = reactive({
  visible: false,
  loading: false,
  taskData: null,
  consumeOption: 'earliest', // earliest, latest, binlog
  binlogPosition: ''
})

// 显示Kafka执行对话框
const showKafkaExecuteDialog = async (taskData) => {
  return new Promise((resolve, reject) => {
    kafkaExecuteDialog.taskData = taskData
    kafkaExecuteDialog.consumeOption = 'none'
    kafkaExecuteDialog.startTime = ''
    kafkaExecuteDialog.visible = true
    kafkaExecuteDialog.loading = false
    
    // 为对话框添加确认和取消的回调
    kafkaExecuteDialog.resolve = resolve
    kafkaExecuteDialog.reject = reject
  })
}

// 处理Kafka任务执行
const handleExecuteKafkaTask = async () => {
  try {
    // 验证时间戳选项
    if (kafkaExecuteDialog.consumeOption === 'timestamp' && !kafkaExecuteDialog.startTime) {
      ElMessage.warning('请选择开始时间')
      return
    }
    
    kafkaExecuteDialog.loading = true
    
    // 构建执行参数
    const executeParams = {
      consumeMode: kafkaExecuteDialog.consumeOption,
      startTime: kafkaExecuteDialog.consumeOption === 'timestamp' ? kafkaExecuteDialog.startTime : null,
      type: 'kafka'
    }
    
    // 调用执行任务API
    await executeTask(kafkaExecuteDialog.taskData.id, executeParams)
    
    ElMessage.success('Kafka消费任务开始执行')
    kafkaExecuteDialog.visible = false
    fetchTaskList()
    
    // 成功时调用resolve
    if (kafkaExecuteDialog.resolve) {
      kafkaExecuteDialog.resolve()
    }
  } catch (error) {
    console.error('执行Kafka消费任务失败：', error)
    ElMessage.error('执行Kafka消费任务失败：' + (error.message || '未知错误'))
    
    // 失败时调用reject
    if (kafkaExecuteDialog.reject) {
      kafkaExecuteDialog.reject(error)
    }
  } finally {
    kafkaExecuteDialog.loading = false
  }
}

// 处理Kafka执行对话框取消
const handleCancelKafkaExecute = () => {
  kafkaExecuteDialog.visible = false
  
  // 取消时调用reject
  if (kafkaExecuteDialog.reject) {
    kafkaExecuteDialog.reject('cancel')
  }
}

// 显示MySQL CDC执行对话框
const showMysqlCdcExecuteDialog = async (taskData) => {
  return new Promise((resolve, reject) => {
    mysqlCdcExecuteDialog.taskData = taskData
    mysqlCdcExecuteDialog.consumeOption = 'none'
    mysqlCdcExecuteDialog.binlogPosition = ''
    mysqlCdcExecuteDialog.visible = true
    mysqlCdcExecuteDialog.loading = false
    
    // 为对话框添加确认和取消的回调
    mysqlCdcExecuteDialog.resolve = resolve
    mysqlCdcExecuteDialog.reject = reject
  })
}

// 处理MySQL CDC任务执行
const handleExecuteMysqlCdcTask = async () => {
  try {
    // 验证binlog选项
    if (mysqlCdcExecuteDialog.consumeOption === 'specific' && !mysqlCdcExecuteDialog.binlogPosition) {
      ElMessage.warning('请输入binlog文件')
      return
    }
    
    mysqlCdcExecuteDialog.loading = true
    
    // 构建执行参数
    const executeParams = {
      consumeMode: mysqlCdcExecuteDialog.consumeOption,
      binlogFile: mysqlCdcExecuteDialog.consumeOption === 'specific' ? mysqlCdcExecuteDialog.binlogPosition : null,
      type: 'mysql-cdc'
    }
    
    // 调用执行任务API
    await executeTask(mysqlCdcExecuteDialog.taskData.id, executeParams)
    
    ElMessage.success('MySQL CDC任务开始执行')
    mysqlCdcExecuteDialog.visible = false
    fetchTaskList()
    
    // 成功时调用resolve
    if (mysqlCdcExecuteDialog.resolve) {
      mysqlCdcExecuteDialog.resolve()
    }
  } catch (error) {
    console.error('执行MySQL CDC任务失败：', error)
    ElMessage.error('执行MySQL CDC任务失败：' + (error.message || '未知错误'))
    
    // 失败时调用reject
    if (mysqlCdcExecuteDialog.reject) {
      mysqlCdcExecuteDialog.reject(error)
    }
  } finally {
    mysqlCdcExecuteDialog.loading = false
  }
}

// 处理MySQL CDC执行对话框取消
const handleCancelMysqlCdcExecute = () => {
  mysqlCdcExecuteDialog.visible = false
  
  // 取消时调用reject
  if (mysqlCdcExecuteDialog.reject) {
    mysqlCdcExecuteDialog.reject('cancel')
  }
}

// 初始化
onMounted(() => {
  fetchDataCenterList()
  fetchTaskList()
})
</script>

<style scoped>
  .task-container {
    padding: 20px;
  }
  
  .table-detail-container {
    padding: 16px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 8px;
    border: 1px solid #e9ecef;
  }
  
  .table-section {
    background: white;
    border-radius: 6px;
    padding: 12px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    border: 1px solid #f0f0f0;
  }
  
  .table-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    font-weight: 600;
    color: #303133;
    font-size: 14px;
  }
  
  .table-header .el-icon {
    margin-right: 6px;
    color: #409eff;
  }
  
  .table-header .kafka-lag {
    margin-left: auto;
  }
  
  .compact-table {
    font-size: 12px;
  }
  
  .compact-table :deep(.el-table__header) {
    background-color: #fafafa;
  }
  
  .compact-table :deep(.el-table__header th) {
    background-color: #fafafa;
    color: #606266;
    font-weight: 600;
    padding: 8px 0;
  }
  
  .compact-table :deep(.el-table__body td) {
    padding: 6px 0;
  }

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 8px 0;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.search-form-item {
  margin-bottom: 0;
  margin-right: 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-select) {
  width: 200px;
}

:deep(.el-select .el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-select .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.batch-actions {
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.template-content {
  margin-top: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.template-header h4 {
  margin: 0;
  color: #606266;
}

.template-actions {
  display: flex;
  gap: 8px;
}

.template-editor {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.template-editor .el-textarea__inner) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  padding: 12px;
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  color: #333;
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}

:deep(.el-descriptions__label) {
  width: 120px;
}

/* 任务描述样式优化 */
:deep(.task-descriptions) {
  margin-bottom: 20px;
}

/* 任务名称行样式 */
:deep(.task-name-item .el-descriptions__label) {
  width: 80px !important;
  min-width: 80px;
}

:deep(.task-name-item .el-descriptions__content) {
  width: calc(100% - 80px) !important;
  word-break: break-word;
  word-wrap: break-word;
}

/* 紧凑型项目样式 */
:deep(.compact-item .el-descriptions__label) {
  width: 80px !important;
  min-width: 80px;
  font-size: 13px;
}

:deep(.compact-item .el-descriptions__content) {
  width: calc(50% - 80px) !important;
  font-size: 13px;
}

.template-tabs {
  margin-top: 20px;
}

.kafka-template {
  margin-top: 16px;
}

/* 添加按钮间距 */
.template-actions .el-button + .el-button {
  margin-left: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 添加编辑相关的样式 */
.el-input {
  width: 100%;
}

/* 添加可编辑名称的样式 */
.editable-name {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
  min-height: 24px;
  width: 100%;
}

.editable-name:hover {
  background-color: #f5f7fa;
}

.task-name-text {
  flex: 1;
  word-break: break-word;
  word-wrap: break-word;
  white-space: normal;
  line-height: 1.5;
  min-height: 20px;
  max-width: 100%;
  overflow-wrap: break-word;
  hyphens: auto;
}

.editable-name .edit-icon {
  color: #909399;
  font-size: 14px;
  opacity: 0;
  transition: opacity 0.3s;
  flex-shrink: 0;
  margin-top: 2px;
}

.editable-name:hover .edit-icon {
  opacity: 1;
}

.name-input {
  width: 100%;
}

.name-input :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.name-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.name-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

.default-value-config {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.default-value-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.default-value-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 